<?php

namespace App\Jobs;



use App\Models\MLM\MLM;
use App\Models\User\User;

class MLMRelateJob extends Job
{


    private $s_parent_id;
    private $user_id;


    public function __construct($s_parent_id, $user_id)
    {
        $this->s_parent_id = $s_parent_id;
        $this->user_id = $user_id;
    }

    public function handle(MLM $MLM, User $user)
    {
        if($this->s_parent_id == $this->user_id){
            return true;
        }
        try{
            $self_mlm = $MLM->where('user_id', $this->user_id)
                ->orWhere('l_parent_id', $this->user_id)
                ->orWhere('m_parent_id', $this->user_id)
                ->orWhere('s_parent_id', $this->user_id)
                ->first();
            if(!empty($self_mlm)){
                return true;
            }
            $parent = $user->where('user_id', $this->s_parent_id)->first();
            if(empty($parent) || empty($parent->is_auth)){
                return true;
            }
            $parent_mlm = $MLM->where('user_id', $this->s_parent_id)->first();
            if(empty($parent_mlm)){
                $MLM->user_id = $this->user_id;
                $MLM->s_parent_id = $this->s_parent_id;
                $MLM->save();
            }else{
                $MLM->user_id = $this->user_id;
                $MLM->s_parent_id = $this->s_parent_id;
                $MLM->m_parent_id = $parent_mlm->s_parent_id;
                $MLM->l_parent_id = $parent_mlm->m_parent_id;
                $MLM->s_agent_id = $parent_mlm->s_agent_id;
                $MLM->m_agent_id = $parent_mlm->m_agent_id;
                $MLM->l_agent_id = $parent_mlm->l_agent_id;
                switch($parent_mlm->agent_level){
                    case 1:
                        $MLM->l_agent_id = $this->s_parent_id;
                        break;
                    case 2:
                        $MLM->m_agent_id = $this->s_parent_id;
                        break;
                    case 3:
                        $MLM->s_agent_id = $this->s_parent_id;
                        break;
                    default:
                        break;
                }
                $MLM->save();
            }
            return true;
        }catch (\Exception $e){
            throw new \Exception('fail on s_parent_id='.$this->s_parent_id.', user_id='.$this->user_id);
        }
    }
}
